package com.itheima.exception;

import com.itheima.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * @author Tang
 * @date 2023/4/11
 */
//@ControllerAdvice + @ResponseBody
@RestControllerAdvice   //捕获controller中所有的异常
@Slf4j
public class GlobalExceptionHandler {

    //SQLIntegrityConstraintViolationException
    //@ExceptionHandler 指定要处理的是哪种异常
    @ExceptionHandler(value = SQLIntegrityConstraintViolationException.class)
    public R doSQLException(SQLIntegrityConstraintViolationException exception){
        String message = exception.getMessage();
        log.warn(message);//Duplicate entry 'zhangsan' for key 'employee.idx_username'
        if (message.contains("Duplicate entry")) {
            String[] s = message.split(" ");
            return R.error(s[2] + "已存在！");
        }
        return R.error("未知异常");
    }

    //处理自定义异常
    @ExceptionHandler(CustomException.class)
    public R doCustomException(CustomException ex) {
        log.warn(ex.getMessage());
        return R.error(ex.getMessage());
    }

}
